package com.sunlee.app.api.exception;


import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.sunlee.common.core.entity.Result;
import com.sunlee.common.core.enums.ErrorCodeEnum;
import com.sunlee.common.core.exception.BusinessException;
import com.sunlee.common.core.exception.util.ExceptionUtils;
import com.sunlee.common.core.utils.HttpContextUtils;
import com.sunlee.common.core.utils.IpUtils;
import com.sunlee.common.service.entity.SysLogErrorEntity;
import com.sunlee.common.service.service.SysLogErrorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpHeaders;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * 异常处理器
 *
 * @author sunlee
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @Resource
    private SysLogErrorService sysLogErrorService;

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<Object> handleRenException(BusinessException ex) {
        saveLog(ex);
        return Result.error(ex.getCode(), ex.getMsg());
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Result<Object> handleDuplicateKeyException(DuplicateKeyException ex) {
        return Result.error(ErrorCodeEnum.DATA_ALREADY_EXISTED_NO_PARAM);
    }

    @ExceptionHandler(Exception.class)
    public Result<Object> handleException(Exception ex) {
        logger.error(ex.getMessage(), ex);
        saveLog(ex);
        return Result.error();
    }

    /**
     * 保存异常日志
     */
    private void saveLog(Exception ex) {
        SysLogErrorEntity log = new SysLogErrorEntity();

        // 请求相关信息
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();

        log.setIp(IpUtils.getIpAddr(request));

        if (!ObjectUtils.isEmpty(request)) {
            log.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));
            log.setRequestUri(request.getRequestURI());
            log.setRequestMethod(request.getMethod());
            Map<String, String> params = HttpContextUtils.getParameterMap(request);
            if (MapUtil.isNotEmpty(params)) {
                log.setRequestParams(JSON.toJSONString(params));
            }
        }

        // 异常信息
        if (ex instanceof BusinessException) {
            BusinessException bex = (BusinessException) ex;
            log.setErrorInfo(bex.getCode() + ":" + bex.getMsg());
        } else {
            log.setErrorInfo(ExceptionUtils.getErrorStackTrace(ex));
        }

        // 时间
        log.setCreateDate(new Date());

        // 保存
        sysLogErrorService.saveOwn(log);
    }
}